<template>
  <div class="page-container">
    <div class="upload-button mb20">
      <el-icon><Upload /></el-icon>
      <span class="ml5">导入</span>
      <input
        id="fileUpload"
        type="file"
        class="inner-upload"
        @change="handleFileUpload"
      >
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column
        type="index"
        label="序号"
        width="100"
      />
      <el-table-column
        prop="ip"
        label="IP地址"
      />
      <el-table-column
        prop="port"
        label="端口"
        width="200"
      />
      <el-table-column
        prop="remark"
        label="备注"
        width="200"
      />
    </el-table>
    <el-pagination
      class="mt20"
      background
      layout="total, sizes, prev, pager, next"
      :total="total"
      :current-page="pageInfo.page"
      :page-size="pageInfo.limit"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { Upload } from '@element-plus/icons-vue'
import { uploadIpAddress, getIpAddressList } from '@/apis/netflow'

const tableData = ref([
])
const pageInfo = ref({
  limit: 10,
  page: 1
})
const total = ref(0)
const handleCurrentChange = value => {
  pageInfo.value.page = value
  initList()
}
const handleSizeChange = value => {
  pageInfo.value.limit = value
  initList()
}
const initList = () => {
  getIpAddressList(pageInfo.value).then(res => {
    tableData.value = res?.list || []
    total.value = res?.total || 0
  })
}

const handleFileUpload = (e) => {
  const fileElement = document.getElementById('fileUpload')
  const file = e.target.files[0]
  const reader = new FileReader()
  reader.readAsText(file)
  reader.onload = e => {
    const fileContent = e.target.result
    const data = JSON.parse(fileContent)
    uploadIpAddress({ proxyServerList: data }).then(res => {
      setTimeout(() => {
        pageInfo.value.page = 1
        initList()
      }, 300)
      fileElement.value = ''
    })
  }
}
onMounted(() => {
  initList()
})
</script>
<style lang="scss" scoped>
.page-container {
  background: #fff;
  padding: 20px;
}
.upload-button {
  padding: 5px 10px;
  position: relative;
  font-size: 14px;
  border-radius: 2px;
  display: inline-flex;
  cursor: pointer;
  background-color: var(--el-color-primary);
  color: #fff;
  align-items: center;
  justify-content: center;
  .inner-upload {
    display: block;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 999;
    opacity: 0;
    cursor: pointer;
  }
}
</style>
